# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        def getLength(head):
            length = 0
            while head:
                head = head.next
                length += 1
            return length

        length = getLength(head)

        def advance(head, n):
            while head and n>0:
                head = head.next
                n -= 1
            return head

        def reverse(head):
            cur = head
            last = None
            for _ in range(k):
                next = cur.next
                cur.next = last
                last = cur
                cur = next
            head.next = cur
            return last

        newHead = ListNode(None)
        newHead.next = head
        head = newHead

        for _ in range(length//k):
            head.next = reverse(head.next)
            head = advance(head, k)
        
        return newHead.next

Solution().reverseKGroup(None, 1)